package dao.impl;

import dao.AddressDao;
import entity.Address;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import service.AddressService;
import util.JDBCUtils;

import java.util.List;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/10/7 17:05
 */
public class AddressDaoImpl implements AddressDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 根据用户id查询地址
     * @param uid
     * @return
     */
    @Override
    public List<Address> findAddressByUid(int uid) {
        String sql = "select a_id aid, u_id uid,a_name aname,a_phone aphone," +
                "a_detail adetail,a_state astate from address where u_id =? order by a_state desc";
        return template.query(sql,new BeanPropertyRowMapper<Address>(Address.class),uid);
    }

    /**
     * 添加一条收货地址数据
     * @param address
     */
    @Override
    public void addAddress(Address address) {
        String sql = "insert into address(u_id,a_name,a_phone,a_detail,a_state) values(?,?,?,?,?);";
        template.update(sql, address.getUid(), address.getAname(), address.getAphone(), address.getAdetail(), address.getAstate());
    }

    /**
     * 删除单条收货地址数据
     * @param aid
     */
    @Override
    public void deleteAddressByAid(int aid) {
        String sql = "delete from address where a_id = ?";
        template.update(sql, aid);
    }

    /**
     * 设置单条默认收货地址
     * @param aid
     */
    @Override
    public void updateAddressToDefaultByAid(int aid) {
        String sql = "update address set a_state =1 where a_id = ?";
        template.update(sql, aid);
    }

    /**
     * 设置多条收货地址为非默认地址
     * @param aid
     */
    @Override
    public void updateAddressToCommonsByAid(int aid,int uid) {
        String sql = "update address set a_state =0 where a_id <> ? and u_id = ?";
        template.update(sql, aid,uid);
    }

    /**
     * 修改收货地址
     * @param address
     */
    @Override
    public void updateAddressByAid(Address address) {
        String sql = "update address set a_name=?,a_phone=?,a_detail=?,a_state =? where a_id = ?;";
        template.update(sql, address.getAname(),address.getAphone(),address.getAdetail(),address.getAstate(),address.getAid());
    }
}
